import styles from './index.module.less';

import { useEffect, useState } from 'react';
import axios from 'axios';
import { fetchRacks } from '@/api/racks';
import { IRack } from '@/types';
import { convertLocalUrl } from '@/utils/FileUtils';

const headers = {
  Authorization:
    'Basic yoLW40nmQqrlJsmeFwRR7dNPQ14C6IVhVgGID8QzxP6GdJcQIliTbVy00Szcu7l5QNHr5dLkQ/bPuF8w79G/cdNZ_r5yU0jl2kkYFpbVR8A=',
};

export const RackList = () => {
  const [parts, setParts] = useState<IRack[]>([]);

  useEffect(() => {
    const getData = async () => {
      const response = await fetchRacks();

      response.data = response.data.filter((item: any) => item.proDrawing);

      const promises = [];

      for (let i = 0; i < response.data.length; i++) {
        const element = response.data[i];
        promises.push(
          axios.get(convertLocalUrl(element.proDrawing), { headers, responseType: 'arraybuffer' })
        );
      }

      const results = await Promise.all(promises);

      for (let i = 0; i < results.length; i++) {
        const element = results[i];

        const blob = new Blob([element.data]);

        response.data[i].proDrawing = URL.createObjectURL(blob);
      }
      setParts(response.data);
    };
    getData();
  }, []);

  const onDragItem = (event: React.DragEvent, item: IRack) => {
    const data = { type: 'rack', item };
    event.dataTransfer.setData('text', JSON.stringify(data));
  };

  return (
    <div className={styles.container}>
      {parts.map(item => (
        <div key={item.id} className={styles.part} draggable onDragStart={e => onDragItem(e, item)}>
          <img src={item.proDrawing} alt="图片" className={styles.icon} />
          <div>{item.hangName}</div>
        </div>
      ))}
    </div>
  );
};
